<template>
  <div>
    <label v-if="label">{{label}}</label>
    <slot></slot>
    <p v-if="errorMessage">{{errorMessage}}</p>
  </div>
</template>

<script>
import Schema from "async-validator";

export default {
  name: "emFromItem",
  data() {
    return {
      errorMessage: ""
    };
  },
  inject: ["form"],
  props: {
    label: {
      type: String,
      default: ""
    },
    prop: String
  },
  mounted() {
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    validate() {
      //执行校验
      const rules = this.form.rules[this.prop];
      //获取数据
      const value = this.form.model[this.prop];

      //校验规则
      const desc = {
        [this.prop]: rules
      };

      const schema = new Schema(desc);
      //参数1是值,参数2是校验错误对象数组
      return schema.validate({ [this.prop]: value }, errors => {
        if (errors) {
          this.errorMessage = errors[0].message;
        } else {
          this.errorMessage = "";
        }
      });
    }
  }
};
</script>

<style scoped>
</style>
